package main

import (
	"golang.org/x/oauth2"
	"net/http"
	"fmt"
	"github.com/vinkdong/gox/log"
	"os"
)

var (
	oauthEndpoint = oauth2.Endpoint{
		AuthURL: os.Getenv("OAUTH_AUTH_URL"),
		TokenURL: os.Getenv("OAUTH_TOKEN_URL"),
	}
	checkTokenUrl = os.Getenv("OAUTH_CHECK_URL")
)

var (
	OauthConfig = &oauth2.Config{
		RedirectURL:  os.Getenv("BASE_URL") + "/authentication",
		ClientID:     os.Getenv("OAUTH_CLIENT_ID"),
		ClientSecret: os.Getenv("OAUTH_CLIENT_SECRET"),
		Scopes:       []string{},
		Endpoint:     oauthEndpoint,
	}
	// Some random string, random for each request
	// todo: change it
	oauthStateString = "ab02l1s"
)

func OauthCheck(w http.ResponseWriter, r *http.Request) bool {
	if r.URL.Path == "/authentication" {
		state := r.FormValue("state")
		if state != oauthStateString {
			log.Errorf("invalid oauth state, expected '%s', got '%s'\n", oauthStateString, state)
		}

		code := r.FormValue("code")
		token, err := OauthConfig.Exchange(oauth2.NoContext,code)
		if err != nil {
			fmt.Println("Code exchange failed with '%s'\n", err)
			http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
			return false
		}

		req,err := http.NewRequest("GET",checkTokenUrl,nil)
		req.Header.Set("Authorization",fmt.Sprintf("bearer %s",token.AccessToken))
		client := http.Client{}
		resp, err := client.Do(req)
		if resp.StatusCode == 200 {
			cookieVal := fmt.Sprintf("_%s", token.AccessToken)
			cookie := &http.Cookie{
				Name:  "_auth_session",
				Value: cookieVal,
			}
			r.AddCookie(cookie)
			validateCookies[cr] = cookieVal
			//todo redirect to before login address
			http.SetCookie(w,cookie)
			http.Redirect(w, r, "", http.StatusTemporaryRedirect)
		}
	} else {
		url := OauthConfig.AuthCodeURL(oauthStateString)
		http.Redirect(w, r, url, http.StatusTemporaryRedirect)
	}
	return false
}